package cn.gbase.jiangsu.data.transfer.action;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.json.simple.JSONObject;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CheckSession;

import cn.gbase.jiangsu.data.transfer.bean.Community;
import cn.gbase.jiangsu.data.transfer.bean.Product;
import cn.gbase.jiangsu.data.transfer.bean.ProductOrder;
import cn.gbase.jiangsu.data.transfer.bean.ProductSellField;
import cn.gbase.jiangsu.data.transfer.bean.ProductSortTreeNode;
import cn.gbase.jiangsu.data.transfer.bean.Supplier;
import cn.gbase.jiangsu.data.transfer.bean.SupplierToCommunity;
import cn.gbase.jiangsu.data.transfer.bean.SupplierUser;
import cn.gbase.jiangsu.data.transfer.bean.SystemLog;
import cn.gbase.jiangsu.data.transfer.common.Constants;
import cn.gbase.jiangsu.data.transfer.service.ProductService;
import cn.gbase.jiangsu.data.transfer.service.ProductSortTreeNodeService;
import cn.gbase.jiangsu.data.transfer.service.SupplierService;
import cn.gbase.jiangsu.data.transfer.service.SystemLogService;
import cn.gbase.jiangsu.data.transfer.vo.ReadyProductVO;

@IocBean
@At("/supplierProduct")
@Filters(@By(type = CheckSession.class, args = { "supplierUser", "/supplierIndex" }))
public class SupplierProductAction {
	@Inject
	private SystemLogService systemLogService;
	@Inject
	private ProductService productService;
	@Inject("java:$config.get('picUpload')")
	private String path;
	@Inject
	private ProductSortTreeNodeService productSortTreeNodeService;
	private final SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
	@Inject
	private SupplierService supplierService;

	/**
	 * 分页查询商品（商品管理页面）.
	 * 
	 * @param currentPage
	 * @param groupId
	 * @param addTime
	 * @param keyword
	 * @param req
	 */
	@At("/listProduct")
	@Ok("jsp:/product/supplierListProduct")
	public QueryResult listProduct(@Param("p") int currentPage, @Param("productCode") String productCode,
			@Param("keyword") String keyword, @Param("nodeId") String nodeId, @Param("upStatus") String upStatus,
			@Param("selectedNodeName") String selectedNodeName, @Param("passStatus") String passStatus,
			@Param("supplierId") String supplierId, @Param("reserveFlag") String reserveFlag,
			@Param("virtualFlag") String virtualFlag, @Param("orderByType") String orderByType,
			@Param("columnInput") String columnInput, HttpServletRequest request, HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("keyword", keyword);
		itemMap.put("nodeId", nodeId);
		itemMap.put("selectedNodeName", selectedNodeName);
		itemMap.put("passStatus", passStatus);
		itemMap.put("upStatus", upStatus);
		itemMap.put("reserveFlag", reserveFlag);
		itemMap.put("virtualFlag", virtualFlag);
		itemMap.put("productCode", productCode);
		itemMap.put("supplierId", String.valueOf(u.getSupplierId()));
		request.setAttribute("formdata", itemMap);

		// 商品分类
		String json = productService.getTreeJsonDataForZTree(1);
		request.setAttribute("treedata", json);

		// 供应商列表
		List<Supplier> supplierList = supplierService.getSupplierList();
		request.setAttribute("supplierList", supplierList);
		request.setAttribute("orderByType", orderByType);
		request.setAttribute("columnInput", columnInput);

		return productService.getProductList(currentPage, productCode, keyword, nodeId, passStatus, upStatus,
				reserveFlag, String.valueOf(u.getSupplierId()), virtualFlag, orderByType, columnInput);

	}

	/**
	 * 批量订单发货
	 */
	@At("/sendOrder")
	@Ok("json")
	public String sendOrder(@Param("idStr") String idStr, HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			supplierService.sendOrder(Integer.valueOf(id));
		}
		return "{id:0}";
	}

	/**
	 * 订单发货
	 */
	@At("/send")
	@Ok("json")
	public String send(@Param("id") int id, HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		supplierService.sendOrder(id);
		return "{id:0}";
	}

	/**
	 * 订单完成
	 */
	@At("/finish")
	@Ok("json")
	public String finish(@Param("id") int id) {
		supplierService.finishOrder(id);
		return "{id:0}";
	}

	/**
	 * 批量订单配货
	 */
	@At("/dependOrder")
	@Ok("json")
	public String dependOrder(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			supplierService.dependOrder(Integer.valueOf(id));
		}
		return "{id:0}";
	}

	/**
	 * 订单配货
	 */
	@At("/depend")
	@Ok("json")
	public String depend(@Param("id") int id) {
		supplierService.dependOrder(id);
		return "{id:0}";
	}

	/**
	 * 跳转到添加商品页面（商品管理）.
	 */
	@At("/toAddProduct")
	@Ok("jsp:/product/supplierEditProduct")
	public void toAddProduct(HttpServletRequest req) {
		// 商品分类
		String json = productService.getTreeJsonDataForZTree(1);
		req.setAttribute("treedata", json);
		UUID uuid = UUID.randomUUID();
		String idNew = uuid.toString();
		req.setAttribute("idNew", idNew);
	}

	/**
	 * 跳转到修改商品页面.
	 */
	@At("/toEditProduct")
	@Ok("jsp:/product/supplierEditProduct")
	public void toEditProduct(@Param("id") int id, HttpServletRequest req) {

		// 要修改的商品
		Product p = productService.getProductById(id);
		p.setNodeId(p.getProductSort());
		if (p.getReserveDate() != null)
			p.setReserveFormatDate(sfd.format(p.getReserveDate()));
		if (p.getReserveStartDate() != null)
			p.setReserveStartFormatDate(sfd.format(p.getReserveStartDate()));
		if (p.getReserveEndDate() != null)
			p.setReserveEndFormatDate(sfd.format(p.getReserveEndDate()));
		ProductSortTreeNode node = productSortTreeNodeService.getStandTreeNode(p.getProductSort());
		if (node != null) {
			p.setSelectedNodeName(node.getName());
		}
		List<ProductSellField> productSellField = productService.getProductSellField(id);
		req.setAttribute("productFieldList", productSellField);
		req.setAttribute("formdata", p);
		Supplier supplier = productService.getSupplierById(p.getSupplierId());
		req.setAttribute("supplier", supplier);
		// 商品分类
		String json = productService.getTreeJsonDataForZTree(1);
		req.setAttribute("treedata", json);
		req.setAttribute("idNew", id);
	}

	/**
	 * 保存商品.
	 * 
	 * @param sp
	 */
	@At("/saveProduct")
	@POST
	@Ok(">>:/supplierProduct/listProduct")
	public void saveProduct(@Param("..") Product product, @Param("idNew") String idNew, @Param("field") String field,
			HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		product.setProductSort(product.getNodeId());
		int stockNumber = 0;
		if (!"".equals(field)) {
			String[] fieldList = field.split("@");
			List<ProductSellField> sfList = new ArrayList<ProductSellField>();
			if (fieldList.length > 0) {
				for (String fieldMap : fieldList) {
					ProductSellField sellField = new ProductSellField();
					String[] split = fieldMap.split(";");
					sellField.setFieldName(split[0]);
					sellField.setFieldValue(split[1]);
					sellField.setStockNumber(Integer.valueOf(split[2]));
					stockNumber += Integer.valueOf(split[2]);
					sfList.add(sellField);
				}
			}
			product.setFieldList(sfList);
		} else {
			product.setFieldList(null);
			stockNumber = product.getStockNumber();
		}
		//重新审核
		product.setPassStatus(0);
		product.setStockNumber(stockNumber);
		productService.updateOrSaveProduct(product, u, idNew);
		SystemLog logger = new SystemLog();
		logger.setOperatorId(u.getId());
		logger.setOperType(1);
		//4是供货商平台
		logger.setOperModular(4);
		logger.setOperContent("供货商用户" + u.getUsername() + "维护商品信息:" + product.getProductName());
		systemLogService.addSystemLog(logger);
	}

	/**
	 * 审核通过商品.
	 * 
	 * @return
	 */
	@At("/pass")
	@Ok("json")
	public String pass(@Param("id") int id) {

		productService.passProduct(id);
		return "{id:0}";
	}

	/**
	 * 上架下架
	 * 
	 * @return
	 */
	@At("/upById")
	@Ok("json")
	public String upById(@Param("id") int id, @Param("upstatus") int upstatus) {

		productService.upProduct(id, upstatus);
		return "{id:0}";
	}

	/**
	 * 审核通过多个商品.
	 * 
	 * @return
	 */
	@At("/passMany")
	@Ok("json")
	public String passMany(@Param("idStr") String idStr) {

		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			productService.passProduct(Integer.valueOf(id));
		}
		return "{id:0}";
	}

	public String findServerPath() {
		String classPath = this.getClass().getClassLoader().getResource("/").getPath();
		try {
			classPath = URLDecoder.decode(classPath, "gb2312");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String[] strPath = classPath.split("/");
		String path = "";
		for (int i = 0; i < strPath.length; i++) {
			if (i > 0 && i <= 3) {
				path = path + strPath[i] + "/";
			}
		}
		return path;
	}

	/**
	 * 上传商品图片.
	 * 
	 * @return
	 */
	@At("/uploadPic")
	@Ok("json")
	public String uploadPic(HttpServletRequest req, HttpSession session, HttpServletResponse reponse) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		//			List<Map> list=new ArrayList<Map>();
		//upload.setHeaderEncoding("UTF-8");
		try {
			List items = upload.parseRequest(req);
			if (null != items) {

				String serverPath = findServerPath();
				// 建立图片文件夹
				String saveurl = serverPath + path;
				File uploadDir = new File(saveurl);
				if (!uploadDir.exists()) {
					uploadDir.mkdirs();
				}
				Iterator itr = items.iterator();
				while (itr.hasNext()) {
					FileItem item = (FileItem) itr.next();
					if (item.isFormField()) {
						continue;
					} else {
						//						  Map<String, String> map = Maps.newHashMap();

						//自由修改处三：可修改上传后的文件命名方式
						SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddkkmmssSSS");//以当前精确到秒的日期为上传的文件的文件名
						String type = item.getName().split("\\.")[1];//获取文件类型
						String fileName = sd.format(new Date()) + "." + type;
						File savedFile = new File(saveurl, fileName);
						item.write(savedFile);
						JSONObject obj = new JSONObject();
						obj.put("name", fileName);
						//							obj.put("id", uuid);
						//						obj.toJSONString();
						return fileName;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

		//		return "{id:0}";
	}

	/**
	 * 删除商品（逻辑删除？）.
	 */
	@At("/delete")
	@Ok("json")
	public String delete(@Param("id") int id) {
		productService.deleteProduct(id);
		return "{id:0}";
	}

	/**
	 * 删除商品（逻辑删除？）.
	 */
	@At("/deleteMany")
	@Ok("json")
	public String deleteMany(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			productService.deleteProduct(Integer.valueOf(id));
		}
		return "{id:0}";
	}

	@At("/orderDetail")
	@Ok("jsp:/product/orderDetail")
	public QueryResult orderDetail(@Param("orderCode") String orderCode, HttpServletRequest request) {
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("orderCode", orderCode);
		request.setAttribute("formdata", itemMap);
		ProductOrder goodsOrder = supplierService.getGoodsOrder(Integer.valueOf(orderCode));
		request.setAttribute("total", goodsOrder.getProductPrice());
		request.setAttribute("orderCode", orderCode);
		return supplierService.getOrderDetail(orderCode);
	}

	@At("/buyOrderDetail")
	@Ok("jsp:/product/productOrder")
	public QueryResult buyOrderDetail(@Param("p") int currentPage, @Param("orderCode") String orderCode,
			@Param("keyword") String keyword, @Param("nodeId") String nodeId, @Param("status") String status,
			@Param("startTime") String startTime, @Param("community") String community,
			@Param("endTime") String endTime, @Param("productId") String productId, HttpServletRequest request,
			HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("productId", productId);
		itemMap.put("orderCode", orderCode);
		itemMap.put("keyword", keyword);
		itemMap.put("startTime", startTime);
		itemMap.put("endTime", endTime);
		itemMap.put("nodeId", nodeId);
		itemMap.put("status", status);
		itemMap.put("community", community);
		request.setAttribute("formdata", itemMap);
		return supplierService.getProductOrderList(productId, orderCode, keyword, nodeId, status, u.getSupplierId(),
				startTime, endTime, community);

	}

	/**
	 * 配货详情
	 * @param currentPage
	 * @param orderCode
	 * @param keyword
	 * @param nodeId
	 * @param status
	 * @param startTime
	 * @param community
	 * @param endTime
	 * @param productId
	 * @param request
	 * @param session
	 * @return
	 */
	@At("/readyOrderDetail")
	@Ok("jsp:/product/readyOrder")
	public void buyOrderDetail(@Param("startTime") String startTime, @Param("community") String community,
			HttpServletRequest request, HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");

		Map<String, String> itemMap = new HashMap<String, String>();
		if (StringUtils.isBlank(startTime))
			startTime = sfd.format(new Date());
		itemMap.put("startTime", startTime);
		request.setAttribute("formdata", itemMap);
		// 配货列表
		List<ReadyProductVO> readyOrderList = supplierService.getReadyOrderList(u.getSupplierId(),
				startTime + " 00:00:00", startTime + " 23:59:59", Constants.ORDER_STATUS_PAID, community);
		request.setAttribute("readyOrderList", readyOrderList);

	}

	@At("/refundProduct")
	@Ok("json")
	public String refundProduct(@Param("details") String details, @Param("startTime") String startTime,
			HttpServletRequest request, HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		String communityId = "";
		List<ReadyProductVO> list = new ArrayList<ReadyProductVO>();
		//多个商品
		String[] products = details.split("@");
		for (String product : products) {
			ReadyProductVO vo = new ReadyProductVO();
			String[] split = product.split(";");
			String productId = split[0];
			String sellNumber = split[1];
			communityId = split[2];
			vo.setProductId(Integer.valueOf(productId.trim()));
			vo.setProductCount(Integer.valueOf(sellNumber.trim()));
			list.add(vo);
		}
		supplierService.checkRefund(u.getSupplierId(), communityId, list, startTime + " 00:00:00",
				startTime + " 23:59:59", Constants.ORDER_STATUS_PAID);
		return "配货完毕";
	}

	/**
	 * 订单列表.
	 * 
	 * @param currentPage
	 * @param orderCode
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param request
	 * @return
	 */
	@At("/listOrder")
	@Ok("jsp:/product/listSupplierOrder")
	public void listOrder(@Param("p") int currentPage, @Param("startTime") String startTime, HttpServletRequest request,
			HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		if (StringUtils.isBlank(startTime))
			startTime = sfd.format(new Date());
		itemMap.put("startTime", startTime);
		request.setAttribute("formdata", itemMap);
		// 订单列表
		List<Community> communityList = supplierService.getOrderCommunity(u.getSupplierId(), startTime + " 00:00:00",
				startTime + " 23:59:59", Constants.ORDER_STATUS_PAID);
		request.setAttribute("communityList", communityList);

	}

	/**
	 * 订单列表.
	 * 
	 * @param currentPage
	 * @param orderCode
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param request
	 * @return
	 */
	@At("/manageOrder")
	@Ok("jsp:/product/manageSupplierOrder")
	public QueryResult manageOrder(@Param("p") int currentPage, @Param("status") String status,
			@Param("community") String community, @Param("startTime") String startTime,
			@Param("address") String address, @Param("orderCode") String orderCode, @Param("endTime") String endTime,
			HttpServletRequest request, HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("status", status);
		itemMap.put("startTime", startTime);
		itemMap.put("endTime", endTime);
		itemMap.put("community", community);
		itemMap.put("address", address);
		itemMap.put("orderCode", orderCode);
		request.setAttribute("formdata", itemMap);

		List<SupplierToCommunity> supplierToCommu = supplierService.getSupplierToCommu(u.getSupplierId());
		request.setAttribute("communityList", supplierToCommu);
		// 订单列表
		return supplierService.getOrderList(currentPage, status, u.getSupplierId(), startTime, endTime, community,
				address, orderCode, Constants.PRODUCT_ORDER);
	}

	/**
	 * 预订订单列表.
	 * 
	 * @param currentPage
	 * @param orderCode
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param request
	 * @return
	 */
	@At("/reserveOrder")
	@Ok("jsp:/product/reserveSupplierOrder")
	public QueryResult reserveOrder(@Param("p") int currentPage, @Param("status") String status,
			@Param("community") String community, @Param("address") String address,
			@Param("orderCode") String orderCode, @Param("startTime") String startTime,
			@Param("endTime") String endTime, HttpServletRequest request, HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("status", status);
		itemMap.put("startTime", startTime);
		itemMap.put("endTime", endTime);
		itemMap.put("community", community);
		itemMap.put("address", address);
		itemMap.put("orderCode", orderCode);
		request.setAttribute("formdata", itemMap);

		List<SupplierToCommunity> supplierToCommu = supplierService.getSupplierToCommu(u.getSupplierId());
		request.setAttribute("communityList", supplierToCommu);
		// 订单列表
		return supplierService.getOrderList(currentPage, status, u.getSupplierId(), startTime, endTime, community,
				address, orderCode, Constants.RESERVE_ORDER);
	}

	/**
	 * 以往订单列表.
	 * 
	 * @param currentPage
	 * @param orderCode
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param request
	 * @return
	 */
	@At("/oldOrder")
	@Ok("jsp:/product/oldSupplierOrder")
	public QueryResult oldOrder(@Param("p") int currentPage, @Param("status") String status,
			@Param("community") String community, @Param("startTime") String startTime,
			@Param("orderCode") String orderCode, @Param("address") String address, @Param("endTime") String endTime,
			HttpServletRequest request, HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("status", status);
		itemMap.put("startTime", startTime);
		itemMap.put("endTime", endTime);
		itemMap.put("orderCode", orderCode);
		itemMap.put("address", address);
		itemMap.put("community", community);
		request.setAttribute("formdata", itemMap);

		List<SupplierToCommunity> supplierToCommu = supplierService.getSupplierToCommu(u.getSupplierId());
		request.setAttribute("communityList", supplierToCommu);
		// 订单列表
		return supplierService.getOldOrderList(currentPage, status, u.getSupplierId(), startTime, endTime, community,
				orderCode, address);
	}

	/**
	 * 跳转到增加产地信息的页面
	 */
	@At("/preCdxxCreate/?")
	@Ok("jsp:/product/cdxxInput")
	public void preCdxxCreate(String productIdStr, HttpServletRequest req) {
		req.setAttribute("productIdStr", productIdStr);
	}

	/**
	 * 保存产地信息
	 */
	@At("/cdxxSave")
	@Ok("jsp:/product/cdxxInput")
	public void cdxxSave(@Param("productIdStr") String productIdStr, @Param("cdxx") String cdxx,
			HttpServletRequest req) {
		String[] productId = productIdStr.split(",");
		for (String id : productId) {
			productService.updateProductCdxx(Integer.parseInt(id), cdxx);
		}
		req.setAttribute("message", "直接关窗口");
	}
}
